import mockRouterMap from '../../mock/routers.js'

const isMock = true

function parseJson(req) {
  return new Promise((resolve) => {
    let body = ''
    let jsonStr = ''
    req.on('data', (chunk) => {
      body += chunk
    })
    req.on('end', () => {
      try {
        jsonStr = JSON.parse(body)
      }
      catch (err) {
        console.log(err)
        jsonStr = ''
      }
      resolve(jsonStr)
    })
  })
}

/** @type {import('vite').Plugin} */
export default {
  name: 'mock-proxy-plugin',
  configureServer({ middlewares }) {
    if (!isMock)
      return
    Object.keys(mockRouterMap).forEach((path) => {
      middlewares.use(path, async (req, res) => {
        // 设置响应头
        res.setHeader('Content-Type', 'application/json')

        console.log(path, 'path')

        const content = mockRouterMap[path]

        if (req.method === 'POST') {
          req.body = await parseJson(req)
        }

        let responseContent

        if (Object.prototype.toString.call(content.default) === '[object Object]') {
          responseContent = content.default
        }
        else if (typeof content.default === 'function') {
          responseContent = await content.default(req, res)
        }
        else if (typeof content === 'function') {
          responseContent = await content(req, res)
        }
        else if (typeof content === 'object' && !content.default) {
          responseContent = content
        }

        // 添加是否为mock的字段
        res.end(JSON.stringify({ ...responseContent, isMock: true }))
      })
    })
  },
}
